package labox.innovation.gameserver.network.clientpackets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.config.Config;
import labox.innovation.gameserver.datatables.AdminCommandAccessRights;
import labox.innovation.gameserver.handler.AdminCommandHandler;
import labox.innovation.gameserver.handler.IAdminCommandHandler;
import labox.innovation.gameserver.model.FuzeWorld;
import labox.innovation.gameserver.model.L2Object;
import labox.innovation.gameserver.model.actor.L2Npc;
import labox.innovation.gameserver.model.actor.instance.FuzeExchangerInstance;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.model.entity.L2Event;
import labox.innovation.gameserver.model.quest.QuestState;
import labox.innovation.gameserver.model.quest.dataset.QuestDataSet;
import labox.innovation.gameserver.network.serverpackets.ActionFailed;

/**
 * bypass命令逻辑处理
 * 
 * @version $Revision: 1.12.4.5 $ $Date: 2005/04/11 10:06:11 $
 */
public final class RequestBypassToServer extends L2GameClientPacket {
	
	private static final String _C__21_REQUESTBYPASSTOSERVER = "[C] 21 RequestBypassToServer";

	private static final Logger _log = LoggerFactory.getLogger(RequestBypassToServer.class.getName());

	// S
	private String _command;

	/**
	 * @param decrypt
	 */
	@Override
	protected void readImpl() {
		String str = readString();
		_command = str.replaceAll("\"", "").replaceAll("bypass -h ", "");
	}

	@Override
	protected void runImpl() {
		FuzePcInstance activeChar = getClient().getActiveChar();

		if (activeChar == null)
			return;

		if (!activeChar.getFloodProtectors().getServerBypass().tryPerformAction(_command))
			return;

		try {
			if (_command.startsWith("admin_")) //&& activeChar.getAccessLevel() >= Config.GM_ACCESSLEVEL)
			{
				String command = _command.split(" ")[0];

				IAdminCommandHandler ach = AdminCommandHandler.getInstance().getAdminCommandHandler(command);

				if (ach == null) {
					if (activeChar.isGM())
						activeChar.sendMessage("The command " + command.substring(6) + " does not exist!");

					_log.warn("No handler registered for admin command '" + command + "'", Config.SERVER_ID, "bypass命令逻辑处理");
					return;
				}

				if (!AdminCommandAccessRights.getInstance().hasAccess(command, activeChar.getAccessLevel())) {
					activeChar.sendMessage("You don't have the access right to use this command!");
					_log.warn("Character " + activeChar.getName() + " tryed to use admin command " + command + ", but have no access to it!", Config.SERVER_ID, "bypass命令逻辑处理");
					return;
				}
				// if (Config.GMAUDIT)
				// GMAudit.auditGMAction(activeChar.getName()+" ["+activeChar.getObjectId()+"]",
				// _command, (activeChar.getTarget() !=
				// null?activeChar.getTarget().getName():"no-target"));

				ach.useAdminCommand(_command, activeChar);
			} else if (_command.equals("come_here") && (activeChar.isGM())) {
				// comeHere(activeChar);
			} else if (_command.startsWith("player_help ")) {
				// playerHelp(activeChar, _command.substring(12));
			} else if (_command.startsWith("npc_"))// npc对话命令处理,
			{
				// if(!activeChar.validateBypass(_command))
				// return;

				int endOfId = _command.indexOf('_', 5);
				String id;
				if (endOfId > 0)
					id = _command.substring(4, endOfId);
				else
					id = _command.substring(4);
				try {
					L2Object object = activeChar.getKnownList().getKnownCharacters().get(Long.parseLong(id));

					if (_command.substring(endOfId + 1).startsWith("event_participate"))
						L2Event.inscribePlayer(activeChar);
					else if (object instanceof L2Npc && endOfId > 0)
						((L2Npc) object).onBypassFeedback(activeChar, _command.substring(endOfId + 1));

					activeChar.sendPacket(ActionFailed.STATIC_PACKET);
				} catch (NumberFormatException nfe) {
				}
			}
			// Navigate through Manor windows
			else if (_command.startsWith("manor_menu_select?")) {
				L2Object object = activeChar.getTarget();
				if (object instanceof L2Npc)
					((L2Npc) object).onBypassFeedback(activeChar, _command);
			} else if (_command.startsWith("Quest "))// 任务命令处理,
			{
				// if(!activeChar.validateBypass(_command))
				// return;

				FuzePcInstance player = getClient().getActiveChar();
				if (player == null)
					return;

				String p = _command.substring(6).trim();
				int idx = p.indexOf(' ');
				if (idx < 0)
					player.processQuestEvent(p, "");
				else
					player.processQuestEvent(p.substring(0, idx), p.substring(idx).trim());
			} else if (_command.startsWith("selcetItemsReward")) {  //-- 选择物品奖励
				FuzePcInstance player = getClient().getActiveChar();
				QuestState qs = player.getQuestState(_command.split(" ")[1].trim());
				qs.setSelectItemId(Integer.parseInt(_command.split(" ")[2].trim()));
			} else if (_command.startsWith("ExchangeItem")) {  //-- 元宝兑换银文
				int exchangeCount = 0;
				String[] commands = _command.split(" ");
				if (commands.length >= 2) 
					exchangeCount = Integer.parseInt(_command.split(" ")[1]);
				
				if (exchangeCount > 0) {
					FuzeExchangerInstance.doExchange(getClient().getActiveChar(), exchangeCount);
				} 
			}
		} catch (Exception e) {
			_log.error(getClient() + " sent bad RequestBypassToServer: ", Config.SERVER_ID, e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see labox.innovation.gameserver.clientpackets.ClientBasePacket#getType()
	 */
	@Override
	public String getType() {
		return _C__21_REQUESTBYPASSTOSERVER;
	}
}
